<?php
/**
 * This page saves edits to an item on the given instance of resourcepage,
 * then redirects back to view.
 * @copyright &copy; 2006 The Open University
 * @author s.marshall@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package resourcepage
 *//** */

    require_once(dirname(__FILE__).'/module_resourcepage.php');
    require_once(dirname(__FILE__).'/../../lib/uploadlib.php');
    require_once(dirname(__FILE__).'/../../lib/filelib.php');
    @include_once(dirname(__FILE__).'/custom_items.php');
    $DASHBOARD_COUNTER=DASHBOARD_RESOURCEPAGE_EDIT;
    
    $module=module_resourcepage::$inst;
 
    $id=required_param('id',PARAM_INT);    // Course Module ID
    $item=required_param('item',PARAM_INT);
    $container=required_param('container',PARAM_INT);
    $itemtype=required_param('itemtype',PARAM_ALPHAEXT);
    $deletefile=optional_param('deletefile',PARAM_PATH);
    $livedateenable=optional_param('livedateenable',null,PARAM_ALPHA);
    $livedateyear=optional_param('livedateyear',null,PARAM_INT);
    $livedatemonth=optional_param('livedatemonth',null,PARAM_INT);
    $livedateday=optional_param('livedateday',null,PARAM_INT);
    $removedateenable=optional_param('removedateenable',null,PARAM_ALPHA);
    $removedateyear=optional_param('removedateyear',null,PARAM_INT);
    $removedatemonth=optional_param('removedatemonth',null,PARAM_INT);
    $removedateday=optional_param('removedateday',null,PARAM_INT);
    $showto=optional_param('showto',null,PARAM_RAW);
    $scrollpos=optional_param('scrollpos',0,PARAM_INT);
    $headinglevel=optional_param('headinglevel',-1,PARAM_INT);
    if($showto!==null) {
        $showto=strtoupper($showto);
        if(!preg_match('/^([A-Z0-9!]+( [A-Z0-9!]+)*)?$/',$showto)) {
            error('Unexpected parameter value for showto. Must be a space-separated list of authids.');
        }
    }
    
     // see bug #3891  set middle default parameter value to null rather than 0
    
    $rights=optional_param('rights',null,PARAM_INT);
       
    // Basic security checks
    $module->obtain_view_info($id,null,$cm,$course,$resourcepage);
    $module->verify_edit_action($cm);

    // Get all item details (could speed this up using a simpler query 
    // but we still need to get the full item and base item details)   
    $content=$module->get_container_items(
        $resourcepage->containerid,
        $resourcepage->deletedcontainerid);
    // Check this item is included
    $parentobj=$content[0]->find_container($container);
    if(!$parentobj) {
        $parentobj=$content[1]->find_container($container);
    }
    if(!$parentobj) {
        error('Container not within module instance');
    }
    $itemobj=&$parentobj->get_item($item);
    if(!$itemobj) {
        error('Item not within container');
    }
    
  
    // set rights to based upon item if $rights same as another item 
    $baseduponitemid = $itemobj->get_field('basedonitem');
    if($baseduponitemid != null) {
    	// we have a based upon item
    	$rs = $module->get_item_fields($baseduponitemid);
    	$basedonrights = $rs->rights;
    
    	// check to see whether rights on based upon item are the same as the based on item    	
    	if($rights == $basedonrights) {
    		// set rights to null
    		$rights = null;
    	} // endif
    	
    } // endif
    		
    		
    
    
    global $CFG;
    
    function update_string_field($itemobj,$field,$newvalue,&$changes) {
        if($newvalue!=$itemobj->get_field($field)) {
            // If they set back to base value, null it
            if($newvalue==$itemobj->get_base_field($field)) {
                $target=null;
            } else {
                $target=$newvalue;
            }
            $changes[$field]=sql_char($target);
        }
    }
    
    function update_int_field($itemobj,$field,$newvalue,&$changes) {
        if($newvalue!==$itemobj->get_field($field)) {
            // If they set back to base value, null it
            if($newvalue===$itemobj->get_base_field($field)) {
                $target=null;
            } else {
                $target=$newvalue;
            }
            $changes[$field]=sql_int($target);
        }
    }
    
    // Update flags if needed
    foreach($_POST as $name=>$value) {
        $matches=array();
        if(preg_match('/^flag_([a-z]+)$/',$name,$matches)) {
            $itemobj->set_flag($matches[1],$value=='1');
        }
    }
    
    // Check changed fields
    $changes=array();
    
    if(isset($livedateenable)) {
        $livedate=
            round((make_timestamp($livedateyear, $livedatemonth, $livedateday)-
            $course->startdate) / (24*60*60)); 
    } else {
        $livedate=null;
    }
    update_int_field($itemobj,'livedate',$livedate,$changes);
    
    if(isset($removedateenable)) {
        $removedate=
            round((make_timestamp($removedateyear, $removedatemonth, $removedateday)-
            $course->startdate) / (24*60*60)); 
    } else {
        $removedate=null;
    }
    update_int_field($itemobj,'removedate',$removedate,$changes);

    update_string_field($itemobj,'showto',isset($showto)&&$showto ? $showto : null,$changes);
    
    update_int_field($itemobj,'rights',$rights,$changes);
    
    function do_description($itemobj,&$changes) {
        $description = stripslashes(required_param('description',PARAM_RAW));

        // Remove surrounding <p></p> if there is no other paragraph involved
        $description=trim(preg_replace('/^\s*<p>((?!.*<p>).*)<\/p>\s*$/s','$1',$description));

        // Some things count as blank 
        if(preg_match('/^\s*(<br\s?\/>|&nbsp;)\s*$/',$description)) {
            $description='';
        }
        
        update_string_field($itemobj,'description',$description,$changes);
    }     
        
    switch($itemtype) {
        case 'weblink' :
            $title=stripslashes(required_param('title',PARAM_RAW));
            update_string_field($itemobj,'title',$title,$changes);
            do_description($itemobj,$changes);
            $weblink=required_param('weblink',PARAM_URL);
            update_string_field($itemobj,'weblink',$weblink,$changes);
            $backbroken=optional_param('backbroken',0,PARAM_INT);
            update_string_field($itemobj,'options',$backbroken?'B':'',$changes);
            break;
        case 'text' :
            $title=stripslashes(required_param('title',PARAM_RAW));
            update_string_field($itemobj,'title',$title,$changes);
            if ($headinglevel != -1) {
                update_int_field($itemobj,'headinglevel',$headinglevel,$changes);
            }
            do_description($itemobj,$changes);
            break;
        case 'crosslink' :
            do_description($itemobj,$changes);
            $linkto=required_param('linkto',PARAM_INT);
            update_int_field($itemobj,'crosslink',$linkto,$changes);
            break;
        case 'file' :
            $title=stripslashes(required_param('title',PARAM_RAW));
            update_string_field($itemobj,'title',$title,$changes);
            do_description($itemobj,$changes);
            if($_FILES['addfile']['size']) {
                // Process file using Moodle upload manager.
                $folder=$module->get_save_folder($course);
                $um=new upload_manager('addfile',false,true,$course); // Renames file if one exists
                if(!$um->save_files($folder)) {
                    error('Failed to save uploaded files');
                }
                $name=$um->get_new_filename();
                if(strpos($folder,$CFG->dataroot)!==0) {
                    error('Folder not within dataroot');
                }
                $mimetype=mimeinfo('type',$name);
                if(!$filesize=filesize($um->get_new_filepath())) {
                    error('File size could not be determined: '.$um->get_new_filepath());
                }
                // Build folder path relative to dataroot (in case items are shared between
                // courses, we don't store them relative to the course's save path)
                $folderrel=substr($folder,strlen($CFG->dataroot)+1);
                
                // Add to database
                $module->add_item_file($item,$folderrel.'/'.$name,$mimetype,$filesize);
            }
            if($deletefile) {
                if(strpos($deletefile,$course->id.'/')!==0) {
                    error("Can't delete files outside course folder"); 
                }
                if($module->delete_item_file($item,$deletefile)) {
                    // Move file to deleted area
                    $folder=$CFG->dataroot.'/'.dirname($deletefile).'/!deleted';
                    $target=$folder.'/'.basename($deletefile);
                    if(!mkdir_recursive($folder)) {
                        error('Failed to create area for deleted files');
                    }
                    if(!rename($CFG->dataroot.'/'.$deletefile,$target)) {
                        error('Failed to move file into deleted area');
                    }
                    // Mark file with time it was 'deleted', we can use this to 
                    // clear out deleted files later if needed
                    if(!touch($target)) {
                        error('Failed to update file date');
                    }
                }
            }
            break;
            
        case 'forumlink' :
            // update forumlink
            if (function_exists('get_forumlink_weblink')) {

                // get title
                $title=required_param('title',PARAM_RAW);

                // update decription
                do_description($itemobj,$changes);
                
                // get weblink          
                $forumlink = get_forumlink_weblink();

                update_string_field($itemobj,'title',$title,$changes);
                // update_string_field($itemobj,'description',$description,$changes);                
                update_string_field($itemobj,'weblink',$forumlink,$changes);

                break;
            } // else drop through
        case 'reference' :
 
            $title=stripslashes(required_param('title',PARAM_RAW));
            //determine if user has manually updated title field and store in options (so style change won't update)
            //if you set title to blank then this flag is removed
            $optionsval='';
            if(($title!=$itemobj->get_field('title')||strpos($itemobj->get_field('options'),'T')!==false) && $title!='') {
                //user has updated title, so ensure option is set to note this
                $optionsval='T';           
            }
            if($title!=''){
                update_string_field($itemobj,'title',$title,$changes);
            }
            do_description($itemobj,$changes);
            $weblink=required_param('weblink',PARAM_URL);
            update_string_field($itemobj,'weblink',$weblink,$changes);
            
            $backbroken=optional_param('backbroken',0,PARAM_INT);
            if($backbroken)
            {
                $optionsval.='B';
            }
            update_string_field($itemobj,'options',$optionsval,$changes);
            break;
        default:
            error('Unsupported item type '.$itemtype);
    }
    
    // Apply changes to DB
    $module->set_item_fields($item,$changes);
         
    // Log and return to view
    add_to_log($course->id, "resourcepage", "edititem", "view.php?id=$cm->id",
        "Edited #".$item,$cm->id);
    redirect('view.php?id='.$cm->id.
        ($deletefile ? '&item='.$item : '').
        ($scrollpos ? '&scrollpos='.$scrollpos : '')); 
?>